package com.weiyirong99.crm.app.server;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.weiyirong99.crm.app.ui.AddCustsActivity;

public class PhoneStateReceiver extends BroadcastReceiver {

    private static final String PHONE_STATE_RECEIVED = "android.intent.action.PHONE_STATE";
    private static int previousState = TelephonyManager.CALL_STATE_IDLE;
    private static int customerid;

    private static PhoneStateReceiver receiver = new PhoneStateReceiver();

    /**
     * 注册
     *
     * @param context
     */
    public static void register(Context context, int customer_id) {
        IntentFilter filter = new IntentFilter();
        filter.setPriority(Integer.MAX_VALUE);
        filter.addAction(PHONE_STATE_RECEIVED);
        context.registerReceiver(receiver, filter);
        customerid = customer_id;
    }

    /**
     * 注销
     *
     * @param context
     */
    public static void unregister(Context context) {
        context.unregisterReceiver(receiver);
    }

    @Override
    public void onReceive(final Context context, Intent intent) {
        // 来电处理逻辑
        checkPhoneState(context, intent);
    }

    /**
     * 检测电话状态
     *
     * @param context
     * @param intent
     */
    private synchronized void checkPhoneState(Context context, Intent intent) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Service.TELEPHONY_SERVICE);
        int callState = telephonyManager.getCallState();
        Log.e("WG", "callState: " + callState);
        switch (callState) {
            case TelephonyManager.CALL_STATE_RINGING:   // 电话进来时
                // 获取电话号码

                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:   // 接起电话时
                Log.e("WG", "接电话");
                break;
            case TelephonyManager.CALL_STATE_IDLE:      //无任何状态时
                Log.e("WG", "无任何状态");
                intent = new Intent(context, AddCustsActivity.class);
                intent.putExtra("customer_id", customerid);
                context.startActivity(intent);
                break;
        }

    }
}
